package com.smile.presenter;

import com.google.gson.Gson;
import com.smile.interf.LoginInterface;
import com.smile.interf.ViewInterface;
import com.smile.model.ReceiveString;
import com.smile.server.ChatManager;

public class LoginPresenter implements ViewInterface {
	
	private LoginInterface loginInterface;
	private boolean isConn = false;
	private Gson gson = new Gson();

	public LoginPresenter(LoginInterface loginInterface) {
		this.loginInterface = loginInterface;
		ChatManager.getCM().setViewInterface(this);
	}
	
	public void setViewInterface(){
		ChatManager.getCM().setViewInterface(this);
	}
	
	public boolean getIsConn(){
		return isConn;
	}
	
	public void conn(){
		isConn = ChatManager.getCM().isConn;
		if(!isConn){
			ChatManager.getCM().connect();
		}
	}
	
	public void closeSocket(){
		ChatManager.getCM().closeSocket();
	}
	
	public void login(String username, String password){
		if(isConn){
			if (username.equals("")) {
				loginInterface.setErrorMessage(1, "请输入昵称");
				loginInterface.setLoginButton(true);
			} else if (password.equals("")) {
				loginInterface.setErrorMessage(2, "请输入密码");
				loginInterface.setLoginButton(true);
			} else {
				loginInterface.setLoginButton(false);
				ChatManager.getCM().login(username, password);
			}
		}
	}
	
	
	
	
	
	
	


	@Override
	public void setMessage(String json) {
		ReceiveString receiveString = gson.fromJson(json, ReceiveString.class);

		switch (receiveString.getCode()) {
		case 1:
			loginInterface.setLoginMessage(true, receiveString.getJson());
			break;
		case 3:
			loginInterface.setErrorMessage(1, "该用户不存在");
			loginInterface.setLoginButton(true);
			break;
		case 2:
			loginInterface.setErrorMessage(2, "密码错误");
			loginInterface.setLoginButton(true);
			break;

		default:
			break;
		}
		
	}

	@Override
	public void setConnMessage(boolean is, String message) {
		if (!is) {
			System.out.println(message);
		}
		isConn = is;
		loginInterface.setConn(isConn);
	}
	
}
